<?php

namespace app\api\controller;

use app\common\Helper;
use app\common\model\Storelabel;
use app\common\model\Storelabelconnect;
use app\common\model\Specialofferrule;
use app\common\model\Storeintroduce;
use app\common\model\Userfocus;
use app\common\model\Userstore;
use app\common\model\Userinstorecount;
use app\common\validate\createStoreValidate;
use app\admin\model\Store as StoreMdl;
use app\admin\model\Storesettlement;
use app\admin\model\Storetradedetail;
use app\admin\model\Ticket;
use app\admin\model\Userconsumedetail;

use think\Db;
use think\Exception;
use think\Request;

class Store extends Base
{

    /**
     * 我的店铺（首页）
     */
    public function myStore(){
        $param = self::getHttpParam();

        /*if (empty($param->storeId)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'storeId 不能为空');
        }*/
        if (empty($param->userId)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'userId 不能为空');
        }

        $userId = $param->userId;
        //$storeId = $param->storeId;
        $userInfo = \app\admin\model\User::get($userId);
        if(!$userInfo){
            return show(config('status.error_code'), '用户不存在', '用户不存在');
        }

        $userstore = Userstore::where('userId', $userId)->find();
        if(!$userstore){
            return show(config('status.error_code'), '暂无店铺', '暂无店铺');
        }

        $storeId = $userstore->storeId;
        $where = [
            //'id' => $param->storeId,
            'id' => $userstore->storeId,
        ];

        $fields = '*';
        $item = StoreMdl::where($where)->field($fields)->find();

        if (empty($item)) {
            return show(config('status.error_code'), self::NOT_DATA, '还没有店铺');
        }

        // 关注人数
        $countFocus = Userfocus::where('storeId', $storeId)->count();
        $item['countFocus'] = $countFocus;
        // 优惠券数量
        $countTicket = Ticket::where('storeId', $storeId)->where('status',['=',5],['=',4],['=',2],'or')->count();
        $item['countTicket'] = $countTicket;

        return show(config('status.success_code'), self::MSG_SUCCESS, $item);
    }

    /**
     * 创建店铺
     */
    public function createMyStore(Request $request){
        (new createStoreValidate())->goCheck();
        if($request->isPost()){
            $param = $request->param();
            Db::startTrans();
            try{
                if(isset($param['store']['id']) && !empty($param['store']['id'])){
                    $storeModel = \app\admin\model\Store::get($param['store']['id']);
                }else{
                    $Store = \app\admin\model\Store::where('contactPhone',$param['store']['contactPhone'])->where('status','<>',2)->find();
                    if($Store){
                        return show(config('status.error_code'),'此手机号已被注册','此手机号已被注册');
                    }
                    $Userstore = Userstore::where('userId',$param['userId'])->find();
                    if($Userstore){
                        return show(config('status.error_code'),'您已经有一个店铺了','您已经有一个店铺了');
                    }
                    $storeModel = new \app\admin\model\Store();
                    $id = Helper::getUUID22();
                    $storeModel->id = $id;
                }

                $storeModel->name = $param['store']['name'];
                $storeModel->imgUrl = $param['store']['imgUrl'];
                $storeModel->addressNumb = $param['store']['addressNumb'];
                $storeModel->phone = $param['store']['phone'];
                $storeModel->businessHours = $param['store']['businessHours'];
                $storeModel->contact = $param['store']['contact'];
                $storeModel->contactPhone = $param['store']['contactPhone'];
                $storeModel->typeId = $param['typeId'];
                $storeModel->province = $param['store']['province'];
                $storeModel->city = $param['store']['city'];
                $storeModel->district = $param['store']['district'];
                $storeModel->businessAreaId = $param['businessAreaId'];
                $storeModel->save();
                if(isset($id) && !empty($id)){
                    $Userstore = new Userstore();
                    $Userstore->userId = $param['userId'];
                    $Userstore->storeId = $id;
                    $Userstore->save();
                }

                Db::commit();
                return show(config('status.success_code'),'创建店铺成功','创建店铺成功');
            }catch (Exception $ex){
                Db::rollback();
                return show(config('status.error_code'),$ex->getMessage(),$ex->getMessage());
            }
        }else{
            return show(config('status.error_code'),'不合法的请求','不合法的请求');
        }

    }

    // 首页根据类型获取店铺
    public function getStoreByType(){
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        /*if (empty($param->storeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'storeId 不能为空');
        }*/
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2, 3])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [];
        if (!empty($param->typeId)) {
            $where['typeId'] = $param->typeId;
        }
        if (!empty($param->keywords)) {
            $where['name'] = ['like', "%{$param->keywords}%"];
        }
        $where['status'] = 1;

        $order = 'countInStore DESC';
        if ($param->type == 3) {
            // 我关注的
            $where = [
                'a.userId' => $param->userId
            ];
            $model = db('userfocus');
            $field = 's.id, s.name, s.imgUrl, s.phone, s.countInStore';
            $result = $model->alias('a')->where($where)->join('store s', 'a.storeId = s.id')->field($field)->limit(0, 20)->order('a.focusTime DESC')->select();
            $total = $model->alias('a')->where($where)->join('store s', 'a.storeId = s.id')->count();
        } else {
            if($param->type == 2){
                $order = 'createDate DESC';
            }

            $model = new StoreMdl();
            $field = 'id, name, imgUrl, phone, countInStore';
            $result = $model->where($where)->field($field)->limit($start, $length)->order($order)->select();
            $total = $model->where($where)->count();
        }

        if (empty($result)) {
            return show(config('status.error_code'), self::NOT_DATA, '未查到店铺');
        }

        foreach ($result as &$item) {
            // 店铺标签
            $storeLabelIds = Storelabelconnect::where('storeId', $item['id'])->field('storeLabelId')->select();
            $storeLabelIds = array_column($storeLabelIds, 'storeLabelId');
            $storelabels = Storelabel::whereIn('id', $storeLabelIds)->field('storeLabel')->select();
            $item['storelabels'] = $storelabels;

            // 店铺券
            $ticket = Home::getTicket($item['id']);
            if($ticket){
                $item['ticketId'] = $ticket['id'];
                $item['ticketName'] = $ticket['name'];
            }
        }

        return showTotal(config('status.success_code'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 店铺详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function getStoreDetails(Request $request){
        $param = $request->param();
        if(empty($param['storeId'])){
            return show(config('status.error_code'),'缺少参数','storeId 不能为空');
        }
        if(empty($param['userId'])){
            return show(config('status.error_code'),'缺少参数','userId 不能为空');
        }

        // 进店记录
        $this->userInStore(['userId' => $param['userId'], 'storeId' => $param['storeId']]);

        $Store = StoreMdl::where(['id'=>$param['storeId'],'status'=>1])->find();
        if($Store){
            // 关注人数
            $countFocus = Userfocus::where('storeId',$param['storeId'])->count();
            $Store['countFocus'] = $countFocus;
            $join = [
                ['__STORELABEL__ s','s.id=a.storeLabelId']
            ];
            $storeLabels = model('storelabelconnect')->alias('a')->where('storeId',$param['storeId'])->join($join)->select();
            if($storeLabels){
                $Store['storeLabels'] = $storeLabels;
            }else{
                $Store['storeLabels'] = null;
            }

            // 是否已关注
            $isFocus = db('userfocus')->where(['userId' => $param['userId'], 'storeId' => $param['storeId']])->find();
            if($isFocus){
                $isFocus = 1;
            }else{
                $isFocus = 2;
            }
            $Store['isFocus'] = $isFocus;

            return show(config('status.success_code'),'ok',$Store);
        }else{
            return show(config('status.error_code'),'店铺异常','店铺异常');
        }
    }

    // 进店记录
    public function userInStore($data){
        if(!$data['userId'] || !$data['storeId']){
            return;
        }
        // 判断是否是进的自己的店
        $userstore = db('userstore')->where('userId', $data['userId'])->find();
        if($data['storeId'] == $userstore['storeId']){
            return;
        }
        Db::startTrans();
        try {
            // 进店次数加一
            StoreMdl::where(['id' => $data['storeId'], 'status' => 1])->setInc('countInStore');

            $userinstoreDB = db('userinstore');
            $info = $userinstoreDB->where($data)->find();

            if($info) {
                $updateData = [
                    'inStoreCount' => $info['inStoreCount'] + 1,
                    'inStoreTime' => date('Y-m-d H:i:s')
                ];
                $userinstoreDB->where($data)->update($updateData);

            } else {
                $updateData = $data;
                $updateData['inStoreStatus'] = 1;
                $updateData['inStoreCount'] = 1;
                $updateData['inStoreTime'] = date('Y-m-d H:i:s');
                $userinstoreDB->insert($updateData);
            }
            $userinstorecount = Userinstorecount::where($data)->whereTime('inStoreTime','today')->find();
            if($userinstorecount){
                $userinstorecount->setInc('inStoreCount', 1);
            }else{
                $UserinstorecountModel = new Userinstorecount();
                $UserinstorecountModel->userId = $data['userId'];
                $UserinstorecountModel->storeId = $data['storeId'];
                $UserinstorecountModel->inStoreCount = 1;
                $UserinstorecountModel->inStoreTime = date('Y-m-d H:i:s',time());
                $UserinstorecountModel->save();
            }
            Db::commit();
        } catch (Exception $e){
            Db::rollback();
        }
    }

    //我是否关注此店铺
    public function getMyFocus(){

    }

    // 获取店铺优惠券
    public function getStoreTickets(Request $request)
    {
        $param = $request->param();
        if (empty($param['storeId'])) {
            return show(config('status.error_code'), '缺少参数', '缺少参数');
        }

        $Ticket = \app\common\model\Ticket::where('storeId', $param['storeId'])->where('status', ['=', 5], ['=', 4], ['=', 2], 'or')->select();

        if ($Ticket) {
            foreach ($Ticket as &$v) {
                $Specialofferrule = Specialofferrule::get($v['specialOfferId']);
                $v['specialOfferRule'] = $Specialofferrule;
            }
            return show(config('status.success_code'), 'ok', $Ticket);
        } else {
            return show(2, '暂无优惠券', null);
        }
    }

    /**
     * 获取店铺介绍
     * @param Request $request
     * @return \think\response\Json
     */
    public function getStoreIntroduce(Request $request){
        $param = $request->param();
        if(empty($param['storeId'])){
            return show(config('status.error_code'),'缺少参数','缺少参数');
        }
        $Storeintroduce = Storeintroduce::get($param['storeId']);
        if($Storeintroduce){
            $Storeintroduce['imgurl'] = explode(',', $Storeintroduce['imgurl']);

            return show(config('status.success_code'),'ok',$Storeintroduce);
        }else{
            return show(config('status.error_code'),'','');
        }
    }

    /**
     * 保存店铺介绍
     */
    public function saveStoreIntroduce(){
        $param = self::getHttpParam();

        if (empty($param->storeId)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'storeId 不能为空');
        }
        if (empty($param->content)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'content 内容不能为空');
        }
        if (empty($param->imgurl)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'imgurl 店铺图片不能为空');
        }

        //$data = (array)$param;
        $data = [
            'storeId' => $param->storeId,
            'content' => $param->content,
            'imgurl' => implode(',', $param->imgurl)
        ];
        $model = new Storeintroduce();
        $info = $model->where(['storeId' => $param->storeId])->find();
        if($info){
            $result = $model->save($data, ['storeId' => $param->storeId]);
        }else{
            $result = $model->save($data);
        }

        if($result === false){
            return show(config('status.error_code'),'保存失败','保存失败');
        }

        return show(config('status.success_code'),'保存成功', '保存成功');
    }

    // 店铺结算记录
    public function storeSettlements(Request $request){
        $param = $request->param();

        $start = 0;
        $length = 20;
        if(empty($param['storeId'])){
            return show(config('status.error_code'), self::NOT_PARAM, 'storeId 不能为空');
        }
        if (!empty($param['start'])) {
            $start = $param['start'];
        }
        if (!empty($param['length'])) {
            $length = $param['length'];
        }

        $Storesettlement = Storesettlement::where('storeId',$param['storeId'])->limit($start,$length)->select();
        $count = Storesettlement::where('storeId',$param['storeId'])->count();
        if($Storesettlement){
            $data['size'] = $count;
            $data['storeSettlements'] = $Storesettlement;

            return show(config('status.success_code'),'ok',$data);
        }else{
            return show(config('status.error_code'),'暂无记录',null);
        }
    }

    // 店铺收入记录
    public function storeTradeIn(Request $request){
        $param = $request->param();

        $start = 0;
        $length = 20;
        if(empty($param['storeId'])){
            return show(config('status.error_code'), self::NOT_PARAM, 'storeId 不能为空');
        }
        if (!empty($param['start'])) {
            $start = $param['start'];
        }
        if (!empty($param['length'])) {
            $length = $param['length'];
        }

        $result = Userconsumedetail::where('storeId', $param['storeId'])->order('payTime DESC')->limit($start, $length)->select();
        $count = Userconsumedetail::where('storeId', $param['storeId'])->count();
        $summoney = Userconsumedetail::where('storeId', $param['storeId'])->sum('payMoney');
        if(!empty($result)){
            foreach ($result as &$item){
                $userInfo = \app\admin\model\User::get($item['userId']);
                $item['user'] = $userInfo;
            }

            $data['total'] = $count;
            $data['data'] = $result;
            $data['summoney'] = $summoney ? $summoney : 0;

            return show(config('status.success_code'), 'ok', $data);
        }else{
            return show(config('status.error_code'), '暂无记录', null);
        }
    }

    // 店铺支出记录
    public function storeTradeOut(Request $request){
        $param = $request->param();

        $start = 0;
        $length = 20;
        if(empty($param['storeId'])){
            return show(config('status.error_code'), self::NOT_PARAM, 'storeId 不能为空');
        }
        if (!empty($param['start'])) {
            $start = $param['start'];
        }
        if (!empty($param['length'])) {
            $length = $param['length'];
        }

        $result = Storetradedetail::where('payStoreId', $param['storeId'])->order('payTime DESC')->limit($start, $length)->select();
        $count = Storetradedetail::where('payStoreId', $param['storeId'])->count();
        $summoney = Storetradedetail::where('payStoreId',$param['storeId'])->sum('payMoney');
        if(!empty($result)){
            $data['total'] = $count;
            $data['data'] = $result;
            $data['summoney'] = $summoney ? $summoney : 0;

            return show(config('status.success_code'), 'ok', $data);
        }else{
            return show(config('status.error_code'), '暂无记录', null);
        }
    }

}